package com.bonc.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.bonc.ProjectConstant;
import com.bonc.entity.InfoEntity;
import com.bonc.repo.SearchRepository;
import com.bonc.service.SearchService;
@Service
public class SearchServiceImpl implements SearchService {
	@Autowired
	SearchRepository esRepo;
	public static final Pattern PATTERN = Pattern.compile(ProjectConstant.SEP_STR);
	public static final Pattern DATE_PATTERN = Pattern.compile(ProjectConstant.DATE_SEP_STR);
	@Override
	public String addInfo(String origin, boolean isFile) {
		if(StringUtils.hasText(origin)) {
			String[] infos;
//			if(origin.trim().startsWith("20")){
//				infos = DATE_PATTERN.split(origin);
//			}else{
//				infos = PATTERN.split(origin);
//			}
			infos = PATTERN.split(origin);
			List<InfoEntity> list = new ArrayList<>();
			for (int i = 0; i < infos.length; i++) {
				String info = infos[i];
				if(!StringUtils.hasText(info) || info.length()<10){
					continue;
				}
				InfoEntity entity;
				if(isFile){
					// 导出文件，时间在分隔字段前
					entity = new InfoEntity();
					if(i>0){
						String pre = infos[i-1];
						int index = pre.lastIndexOf("\n");
						String dateStr = index>0 ? pre.substring(index) : pre;
						entity.setDate(dateStr);
					}
					int first = info.indexOf("\n");
					int index = info.lastIndexOf("\n");
					entity.setInfo(first>0&&first!=index ? info.substring(first+1, index) : info);
				}else{
					// 复制聊天记录，时间在分隔字段后
					entity = new InfoEntity(info);
				}
				list.add(entity);
			}
			//新增前删除，避免重复
			esRepo.deleteAll();
			esRepo.saveAll(list);
		}
		return "ok";
	}   

	@Override
	public String searchInfo(String cond) {
		QueryBuilder builder = QueryBuilders.matchQuery("info", cond);
		Iterable<InfoEntity> its=esRepo.search(builder);
		List<InfoEntity> list = new ArrayList<>();
		its.forEach(list::add);
		return JSON.toJSONString(list);
	}
	
}
